package com.biostime.qdingding.modules.qd.service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.biostime.qdingding.modules.qd.api.dto.SmsDto;

@Service
public class SmsService {
	
	public static Logger logger=Logger.getLogger("api"); 
	
	@Value("${sms.host}")
	private String HOST;
	@Value("${sms.userid}")
	private String USERID;
	@Value("${sms.password}")
	private String PASSWORD;
	@Value("${sms.sendmsgpath}")
	private String SEND_MSG_URL;
	
	private final String MSG_TEMPLATE="您的验证码是:XXXX";
	
	private String post(String url,String requestBody){
		URL realUrl=null;
		HttpURLConnection connection=null;
		OutputStream os=null;
		InputStream is=null;
		byte[] b=new byte[4096];
		int offset=0,count=0;
		try {
			realUrl = new URL(url);
			connection = (HttpURLConnection)realUrl.openConnection();
			connection.setConnectTimeout(3000);
			connection.setDoOutput(true);
			connection.connect();
			os=connection.getOutputStream();
			os.write(requestBody.getBytes("utf-8"));
			os.flush();
			os.close();
			is=connection.getInputStream();
			while(true){
				int byte_length=b.length;
				count=is.read(b,offset,byte_length-offset);
				if(count!=-1)offset+=count;
				if(count==-1)break;//由于数据包不一定一次就能发送完，所以必须读到文件尾才能确定读完
				if(byte_length-offset==0){//当数组长度不足时，增加其长度
					byte[] newByte=new byte[byte_length+4096];
					System.arraycopy(b, 0, newByte, 0, byte_length);
					b=newByte;
				}
			}
			is.close();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				if(is!=null)is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}finally{
				if(connection!=null)connection.disconnect();
			}
		}
		String s=null;
		try{
			s=new String(b,0,offset,"utf-8");
		}catch(Exception e){
			e.printStackTrace();
		}
		return s;
	}
	public SmsDto sendMsg(String tel,String code){
		String msg=MSG_TEMPLATE.replace("XXXX", code);
		String url=HOST+SEND_MSG_URL;
		String requestBodyTemplate="userid=USERID&password=PASSWORD&destnumbers=TEL&msg=MSG";
		String requestBody=requestBodyTemplate.replace("USERID", USERID).replace("PASSWORD", PASSWORD).replace("TEL", tel).replace("MSG", msg);
		String smsRet=post(url,requestBody);
		SmsDto sd=null;
		ByteArrayInputStream bais=null;
		try {
			JAXBContext jaxb=JAXBContext.newInstance(SmsDto.class);
			bais=new ByteArrayInputStream(smsRet.getBytes("utf-8"));
			sd=(SmsDto)jaxb.createUnmarshaller().unmarshal(bais);
		} catch (JAXBException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} finally{
			if(bais!=null)
				try {
					bais.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
		logger.info("成功发送短信,电话:"+tel+",验证码:"+code+",结果:"+smsRet);
		return sd;
	}
	public String getRandomText(){
		long timestamp=System.currentTimeMillis();
		return String.format("%04d", timestamp%10000);
	}
}
